// index.js
// const app = getApp()
const { envList } = require('../../envList.js');
const api = require('../../api')
import { request,formatTime2 } from '../../util'
import { CanvasDraw } from '../examples/canvasDraw'

Page({
  data: {
    canvasEle:null,
    canvasEle2:null,
    active:0,
    stashData:[],
    startX: 0, // 保存 X 坐标
    startY: 0, // 保存 Y 坐标
    stashImg:"",
    colorData: {
      //基础色相，即左侧色盘右上顶点的颜色，由右侧的色相条控制
      hueData: {
          colorStopRed: 255,
          colorStopGreen: 0,
          colorStopBlue: 0,
      },
      //选择点的信息（左侧色盘上的小圆点，即你选择的颜色）
      pickerData: {
          x: 0, //选择点x轴偏移量
          y: 480, //选择点y轴偏移量
          red: 0, 
          green: 0,
          blue: 0, 
          hex: '#000000'
      },
      //色相控制条的位置
      barY: 0,
      show:false
  },
  rpxRatio: 1, //此值为你的屏幕CSS像素宽度/750，单位rpx实际像素
  rgb: 'rgb(255,250,250)',
  pick: false,
  strHex:"#000000",
  arrdraw:[],
  reloadArrdraw:[],
  addbusiness:false,
  show:false,
  show2:false,
  addbusinessFrom:{
    inventoryDraw:"",
    vageId:0,
    inventoryNum:"",
    stashId:0
  },
  vagelist:[],
  userInfo:wx.getStorageSync('userInfo'),
  lastcheck:-1,
  checkStashId:0,
  StartX:0,
  StartY:0,
  dataList: [
    {
      type: 'text',
      text: '可拖拽文字',
      fontSize: 18,
      fontWeight: 'normal',
      fontStyle: 'normal',
      startX: 1,
      startY: 1,
      x: 60,  //x轴偏移量
      y: 60,  //Y轴偏移量
      angle: 0, //旋转角度
    }
  ]
  },
  //颜色选择
  pickColor(e) {
    console.log("color："+e.detail.color);
    // this.setData({
    //   rgb: e.detail.color
    // })
    this.colorRgb(e.detail.color)
    console.log(this.data.strHex)
    this.data.canvasEle.strokeStyle = this.data.strHex;
    // this.setData({
    //   rgb:this.data.strHex
    // })
     // 开始绘制
  this.data.canvasEle.beginPath();
  },
  //仓库选择
  onChangeStash(e){
    this.setData({
      stashImg:this.data.stashData[e.detail.index].stashImg,
      checkStashId:this.data.stashData[e.detail.index].stashId
    })
    wx.createSelectorQuery()
      .select("#myCanvas")
      .fields({ node: true, size: true })
      .exec((res)=>{
        const canvasNode = res[0].node
        const img= canvasNode.createImage();
        img.src = this.data.stashImg;
        img.onload = () => {
          console.log("图片加载完成",this.context)
            this.data.canvasEle.drawImage(
              img,
                0,
                0,
                res[0].width,
                res[0].height,
            )
            }
      })
   
},
resetAll(){
  console.log(this.data.arrdraw)
  //this.data.canvasEle.clearRect
},
drawShape(opt, isAddChild = true){
  if (opt.points.length < 3) return
    const tempObj = { type: 'Shape', angle: opt.angle, points: opt.points }
    this.rotateDraw(tempObj, () => {
      this.ctx.beginPath()
      this.ctx.lineWidth = opt.style.strokeWidth ?? 1
      this.ctx.fillStyle = opt.style.fill
      this.ctx.strokeStyle = opt.style.stroke ?? '#000'

      // 设置虚线
      if (opt.style.stroke && opt.style.lineDash && opt.style.lineDash.length > 0) {
        this.ctx.setLineDash(opt.style.lineDash)
      }

      for (let i = 0; i < opt.points.length; i++) {
        const p = opt.points[i]
        if (i === 0) {
          this.ctx.moveTo(p.x, p.y)
        } else {
          this.ctx.lineTo(p.x, p.y)
        }
      }
      this.ctx.closePath()
      if (opt.style.stroke) {
        this.ctx.stroke()
        this.ctx.setLineDash([])
      }
      if (opt.style.fill) {
        this.ctx.fill()
      }
    })

    if (isAddChild) {
      return this.addChild('Shape', opt)
    }
},
stardraw(){
   this.setData({
    addbusiness:true
   })
},
addText(){
  this.setData({
    show:true
  })
},
onChange(e){
   console.log(e);
    this.setData({
      "addbusinessFrom.inventoryNum":e.detail
      //"dataList":this.data.dataList.push(arr)
   })
   console.log(this.data.dataList)
},
sureText(e){
 console.log(e);
 this.data.canvasEle2.beginPath();
 console.log(this.data.canvasEle2);
 //this.data.canvasEle2.fillStyle = "red";// 设置填充画笔颜色为红色，即字体颜色
 this.data.canvasEle2.font = "18px Georgia";// 设置字体大小
 this.data.canvasEle2.lineWidth = 1;// 设置字体大小
 this.data.canvasEle2.strokeStyle = "#333";// 设置字体大小
 this.data.canvasEle2.fillText(this.data.addbusinessFrom.inventoryNum,136,89);// 绘制 "实心" 文字
  // fillText(str, x, y, maxW)：str绘制的文字，(x, y)起始坐标，maxW是最大宽度，绘制文字超过该宽度则不显示。
  this.data.canvasEle2.closePath();
  var arr = {
    type: 'text',
    text: this.data.addbusinessFrom.inventoryNum,
    fontSize: 18,
    fontWeight: 'normal',
    fontStyle: 'normal',
    startX: 1,
    startY: 1,
    x: 60,  //x轴偏移量
    y: 60,  //Y轴偏移量
    angle: 0, //旋转角度
  }
  var dataList = this.data.dataList;
  dataList.push(arr)
  this.setData({
    show:false,
    "dataList":dataList
  })
},
onTouchmove2(e){
  console.log(e);
  console.log(this.data.StartX)
  // document.onmousemove = function (ev) {
  //   console.log(ev);
  // }
   this.setData({
    "StartX":e.changedTouches[0].screenX - e.changedTouches[0].pageX,
    "StartY":e.changedTouches[0].screenY - e.changedTouches[0].pageY
   })
  //  this.setData({
  //   "StartX":e.currentTarget.offsetLeft,
  //   "StartY":e.currentTarget.offsetTop
  //  })
  //  this.data.canvasEle2.style.left = StartX
  //  this.data.canvasEle2.style.top = StartY
  //  this.data.canvasEle2.fillRect()
  //  console.log(this.data.canvasEle2)
  //  let initleft = Number((this.data.canvasEle2.style.left).replace('px',''))
  //  let inittop = Number((this.data.canvasEle2.style.top).replace('px',''))
  //  console.log(StartX);
  //  console.log(StartY);
  //  console.log(initleft);
  //  console.log(inittop);
},
colorRgb (color) {
  var reg = /^(rgb|RGB)/;
  if (reg.test(color)) {
    var strHex = "#";
    // 把RGB的3个数值变成数组
    var colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
    // 转成16进制
    for (var i = 0; i < colorArr.length; i++) {
      var hex = Number(colorArr[i]).toString(16);
      if (hex === "0") {
        hex += hex;
      }
      strHex += hex;
    }
    this.setData({
      strHex:strHex
    })
  }
},
selectColorEvent(){
   this.setData({
    strHex:"#000000"
   })
},
selectColorEvent2(){
  this.setData({
    strHex:"#EE2C2C"
  })
},

onClose(){
  this.setData({
    show:false
  })
},
onClose2(){
  this.setData({
    show2:false
  })
},
handDraw(){
  this.setData({
    show:true,
    Zindex:0,
    pick:true
  })
},
  selectStash(){
    var that = this;
     request(api.selectStash).then(function(res){
       console.log(res);
       that.setData({
         stashData:res.data,
         checkStashId:res.data[0].stashId,
         reloadArrdraw:res.data[0].children
       })
     })
  },
  drawhz(darw){
     var that =this;
       this.data.canvasEle.lineWidth =5; // 笔粗细
        this.data.canvasEle.strokeStyle =this.data.strHex; // 画笔颜色
        this.data.canvasEle.lineJoin="round"; //设置末端
        this.data.canvasEle.lineCap = 'round'; // 设置笔头
        
        //console.log(this.data.arrdraw);
        // 开始绘制
        this.data.canvasEle.beginPath();

    var strtext="";
    var strdate="";
    var x=0;
    var y=0;
     setTimeout(function() {
      darw.forEach(element=>{
        var index=0;
        strtext="";
        strdate="";
        x=0;
        y=0;
        strtext=element.vegetables;
        strdate=element.inventoryDate.split(" ")[0];
        var arr = JSON.parse(element.inventoryDraw);
        console.log(arr.length/2)        
        //x += arr[(arr.length/2)].startX - 60;
        
        y = arr[arr.length/2].startY;
        //y = arr[arr.length].startY;
        console.log(arr.length);
        arr.forEach(element=>{
            that.data.canvasEle.moveTo(arr[index].startX, arr[index].startY);
            x+=arr[index].startX;
            index++;
            if (index<=(arr.length-1)) {
            that.data.canvasEle.lineTo(arr[index].startX, arr[index].startY);
            that.data.canvasEle.stroke();
            x+=arr[index].startX;
           }
       })
       console.log(x/arr.length);
       //console.log(y)
      that.data.canvasEle.font="18px Georgia";
      that.data.canvasEle.fillText(strtext, (x), y/2);
      that.data.canvasEle.fillText(strdate, (x), y/1.5);
     })
     },2000)
  },
  onLoad(){
    this.selectStash();
    this.initCanvas();
     //设置rpxRatio
    //  setTimeout(function(){
    //   wx.getWindowInfo()({
    //     success(res) {
    //         _this.setData({
    //             rpxRatio: res.screenWidth / 750
    //         })
    //     }
    // })
    //  },2000)
  },
  initCanvas() {
     wx.createSelectorQuery()
      .select("#myCanvas")
      .fields({ node: true, size: true, rect: true })
      .exec((res) => {
        const ele = res[0].node
        const context = ele.getContext("2d")
        const dpr = wx.getWindowInfo().pixelRatio
        ele.width = res[0].width * dpr
        ele.height = res[0].height * dpr
        
        const img= ele.createImage();
        img.src = this.data.stashData[0].stashImg;
        img.onload = () => {
          console.log("图片加载完成",this.context)
          context.drawImage(
              img,
                0,
                0,
                res[0].width,
                res[0].height,
            )}
      context.scale(dpr, dpr);
        this.setData({          
          canvasEle:context
        })
        console.log(this.data.reloadArrdraw);
        this.drawhz(this.data.reloadArrdraw);
      })

      wx.createSelectorQuery()
        .select("#myCanvass2")
        .fields({node:true,size:true,rect:true})
        .exec((res)=>{
          console.log(res);
          const ele = res[0].node
          const context = ele.getContext("2d")
          this.setData({          
            canvasEle2:context
          })
        })
  },
  onTouchstart(e) {
    if (this.data.addbusiness) {
      var obj = {
        startX: e.changedTouches[0].x,
        startY: e.changedTouches[0].y
      }
      this.data.arrdraw.push(obj);
      this.setData({
        startX : e.changedTouches[0].x,
        startY :e.changedTouches[0].y
      })
    // 进行一些绘制的准备工作（笔粗细、颜色、笔头）
    // 如果使用过微信小程序旧版接口的同学，需要注意
    // 现在很多方法都没有，已经停止维护
    this.data.canvasEle.lineWidth =5; // 笔粗细
    this.data.canvasEle.strokeStyle =this.data.strHex; // 画笔颜色
    this.data.canvasEle.lineJoin="round"; //设置末端
    this.data.canvasEle.lineCap = 'round'; // 设置笔头
    
    //console.log(this.data.arrdraw);
    // 开始绘制
    this.data.canvasEle.beginPath();
    }
  },
  onTouchmove(e) {
    if (this.data.addbusiness) {
      console.log('触摸移动：', e)
    // 移动的时候，得到的实时的坐标
  var startX = e.changedTouches[0].x;
  var startY = e.changedTouches[0].y;
  var obj = {
    startX,
    startY
  }
  this.data.arrdraw.push(obj);
  // 首先将画笔移动到手指按下的地方
  this.data.canvasEle.moveTo(this.data.startX, this.data.startY);
  // 描线，根据实时的坐标进行进行描线
  this.data.canvasEle.lineTo(startX, startY);
  // 绘制直线
  this.data.canvasEle.stroke();

  // 注意，这个步骤也很重要，需要更新起始坐标
  this.setData({
    startX:startX,
    startY:startY
  })
    }
  },
  onTouchend(e) {
    if (this.data.addbusiness) {
      console.log(JSON.stringify(this.data.arrdraw).length)
    this.data.canvasEle.closePath();
    this.setData({
      addbusiness:false,
      "addbusinessFrom.inventoryDraw":this.data.arrdraw
    })
    }
  },
  vagelData() {
    var that = this;
    console.log(this.data.userInfo.id);
    request(api.vagedata,{userId: this.data.userInfo.id, roleId: this.data.userInfo.roleId}).then(function (res) {
      var data = res.data.data;
      var obj=[];
      data.forEach(element => {
        element.ischeck=false;
        obj.push(element);
      });
      that.setData({
        vagelist: obj
      })
    })
  },
   /** 组件方法-绘制多边形 */
   addShape() {
     //添加库存
     this.vagelData();
     this.setData({
       show2:true
     })
  },
  draw() {
    // 1.默认绘图方式-圆形
    // const { ctx } = this.canvasDraw
    // ctx.beginPath()
    // ctx.strokeStyle = '#000'
    // ctx.arc(50, 50, 50, 0, 2 * Math.PI)
    // ctx.stroke()
    // ctx.closePath()
  },
  checkvage(e){
    var id = e.currentTarget.dataset.index;
    var obj = `vagelist[${id}].ischeck`
    this.setData({
      [obj]:true,
      'addbusinessFrom.vageId':this.data.vagelist[id].vegetablesId
    })
    if (this.data.lastcheck>=0) {
    var obj2 = `vagelist[${this.data.lastcheck}].ischeck`
    this.setData({
      [obj2]:false,
      lastcheck:id
    })
    }else{
      this.setData({
        lastcheck:id
      })
    }
    console.log(this.data.addbusinessFrom);
  },
  //选择改色时触发（在左侧色盘触摸或者切换右侧色相条）
onChangeColor(e) {
  console.log(e);
  //返回的信息在e.detail.colorData中
  this.setData({
    colorData: e.detail.colorData
  })
},
sureAdd(){
  console.log(this.data.addbusinessFrom)
  console.log(JSON.stringify(this.data.arrdraw.length).length);
  this.setData({
    "addbusinessFrom.stashId":this.data.checkStashId
  })
  request(api.addInventory,{str:JSON.stringify(this.data.addbusinessFrom)},"post").then(function (res) {
      console.log(res);
  })
}
});
